package cn.tony.game.super_tank;

import java.awt.Graphics;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JPanel;

public class MainView extends JPanel {

	public volatile List<Drawable> drawables = new ArrayList<Drawable>();
	
	
	private static final long serialVersionUID = -5639694648439682825L;

	public MainView(List<Drawable> drawable) {
	    
		this.drawables = drawable;
		this.setBounds(0, 0, Game.W, Game.H);
		this.setBackground(Game.black);
		this.setVisible(true);

		new Thread(new Runnable() {
			public void run() {
				while (true) {
					try {
						Thread.sleep(1000 / 60);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					repaint();
				}
			}
		}).start();
	}

	@Override
	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		for (int i = drawables.size() - 1; i >= 0; i--) {
			Drawable c = (Drawable) drawables.get(i);
			if (!c.isAlive) {
				drawables.remove(i);
				continue;
			}
			c.paint(g);
			checkHit(c);
		}

	}

	private void checkHit(Drawable c) {
		for (int i = drawables.size() - 1; i >= 0; i--) {
			Drawable d = drawables.get(i);
			if (d.isHit(c)) {
				showBoom(c);
			}
			if (c.isHit(d)) {
				showBoom(d);
			}
		}
	}

	private void showBoom(Drawable d) {
		Boomshakalaka boomshakalaka = new Boomshakalaka();
		boomshakalaka.syncLocation(d);
		drawables.add(boomshakalaka);
	}

}
